"use strict";
// 使用方法：
//   1.安装依赖
//   npm i nodemailer;
//   2.执行下面的命令。如果没有附件，就不需要"$attachment"参数
//   node mail_from_qq.js "$from" "$to" "$smtpServer" "$password" "$subject" "$body" "$attachment"

const process=require('process');
const nodemailer = require("nodemailer");
/*
for (let i=2 ; i<process.argv.length ; i++ ){
  console.log(i+': '+process.argv[i]);
}
*/
const transporter = nodemailer.createTransport({  // 可用的项: https://nodemailer.com/smtp/
  host: process.argv[4],
  port: 587,
  // proxy: 'http://proxy-host:1234', // 指定代理服务器和端口
  secure: false,
  // tls: {
  //   rejectUnauthorized: false,     // 这三行表示: Allow self-signed certificates
  // },
  auth: {
    user: process.argv[2],
    pass: process.argv[5]
  }
});

// async..await is not allowed in global scope, must use a wrapper
async function main() {
  if(process.argv[8]){
    // send mail with defined transport object
    const info = await transporter.sendMail({   // 可用的项: https://nodemailer.com/message/
      from: process.argv[2],
      to: process.argv[3],                      // 可以是多个收件人，如：'a@qq.com, b@139.com'
      subject: process.argv[6],
      attachments: [{path: process.argv[8]}],   // 关于附件，参考: https://nodemailer.com/message/attachments/
      //text: "Hello world?",                   // plain text body
      html: process.argv[7]                     // html body
    });
  }else{
    const info = await transporter.sendMail({
      from: process.argv[2],
      to: process.argv[3],
      subject: process.argv[6],
      //text: "Hello world?",
      html: process.argv[7]
    });
  }
  
/*
  //console.log("Message sent: %s", info.messageId);  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
  for(let i in info){
    console.log(i+': '+info[i]);
  }

accepted: houseschan@houseschan.cn
rejected: 
ehlo: PIPELINING,SIZE 15728640,ETRN,AUTH PLAIN LOGIN,ENHANCEDSTATUSCODES,8BITMIME,DSN,SMTPUTF8
envelopeTime: 579
messageTime: 380
messageSize: 678
response: 250 2.0.0 Ok: queued as 4QwzT41sp8z2xF9
envelope: [object Object]
messageId: <06b2ed99-c4a7-1547-5d50-c37dccc73063@houseschan.cn>
*/
}

main().catch(console.error);
//console.log('已发送');        // 先输出‘已发送’，再输出info[i]
